package com.srwl.mytx.adapter;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.AdvertisementActivity;
import com.srwl.mytx.activity.OrderDetailActivity;
import com.srwl.mytx.activity.SetAdvertisementContentActivity;
import com.srwl.mytx.activity.TopicDetailsActivity;
import com.srwl.mytx.domain.Advertisement;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Orders;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.OrderService;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.OfferDialogV1;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class OrderRecordAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = "DonationRecordAdapter";
    public static final int REQUEST_CODE_SET_ADVERTISEMENT = 1000;
    public static final int REQUEST_CODE_OFFER = 2000;
    public static final int REQUEST_CODE_TO_ORDER_DETAIL = 1;
    private static final int ITEM_TYPE_NO_DATA = -1;
    private final List<Orders> ordersList;
    private final Context context;


    public OrderRecordAdapter(Context context, List<Orders> ordersList) {
        this.ordersList = ordersList;
        this.context = context;

    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case ITEM_TYPE_NO_DATA:
                return new NoDataViewHolder(LayoutInflater.from(context).inflate(R.layout.no__data__layout, parent, false));
            default:
                return new OfferViewHolder(LayoutInflater.from(context).inflate(R.layout.my_offer_record_item_layout, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        if (ordersList.size() == 0) {
            return;
        }
        final Orders order = ordersList.get(position);
        OfferViewHolder viewHolder = (OfferViewHolder) holder;
        Integer type = order.getType();
        if (type == Constant.ORDER_TYPE_TO_ADVERTISEMENT) {
            showAdvertisementOrder(order, viewHolder);
        } else if (type == Constant.ORDER_TYPE_TO_AUCTION_TOPIC) {

            Topic topic = order.getTopic();
            viewHolder.tv_title.setText(topic.getTitle());
            viewHolder.tv_orderType.setText("[拍卖]");
            //  viewHolder.tv_title.setOnClickListener((view) -> getFullTopic(topic.getId()));
            viewHolder.tv_maxAmount.setText(Utils.numberFormat(topic.getPrice()));
            switch (order.getStatus()) {
                case Constant.ORDER_STATUS_CONFLICT:
                    viewHolder.tv_status.setText("问题处理中...");
                    toOrderDetail(order, viewHolder, "查看订单详情");
                    break;
                case Constant.ORDER_STATUS_OFFER_SUCCESS:
                    viewHolder.tv_myAmount.setTextColor(context.getResources().getColor(R.color.text_black));
                    viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.rp_money_red_light));
                    viewHolder.tv_status.setText("竞价成功");
                    viewHolder.tv_tips.setVisibility(View.VISIBLE);
                    toOrderDetail(order, viewHolder, "支付订单");
                    break;
                case Constant.ORDER_STATUS_OFFER_FAIL:
                    viewHolder.tv_myAmount.setTextColor(context.getResources().getColor(R.color.text_gray));
                    viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_gray));
                    viewHolder.tv_status.setText("竞价失败");
                    viewHolder.tv_tips.setText("查看出价记录");
                    viewHolder.tv_tips.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            OfferDialogV1 offerDialog = new OfferDialogV1(context, topic, new OfferDialogV1.InteractionListener() {
                                @Override
                                public void onOfferSuccess(double amount) {
                                    order.setAmount(amount);
                                    topic.setPrice(amount);
                                    notifyItemChanged(position);
                                }
                            });
                            offerDialog.show();
                        }
                    });
                    break;

                case Constant.ORDER_STATUS_PAID:
                    if (order.getSendStatus() != null && order.getSendStatus() == Constant.ORDER_SEND_STATUS_SENT) {
                        viewHolder.tv_status.setText("已发货");
                    } else {
                        viewHolder.tv_status.setText("已支付");
                    }
                    toOrderDetail(order, viewHolder, "查看订单详情");
                    break;
                case Constant.ORDER_STATUS_SENT:
                    viewHolder.tv_status.setText("已发货");
                    toOrderDetail(order, viewHolder, "查看订单详情");
                    break;
                case Constant.ORDER_STATUS_EXPIRED:
                    viewHolder.tv_status.setText("已过期");
                    toOrderDetail(order, viewHolder, "查看订单详情");
                    break;
                case Constant.ORDER_STATUS_BUYER_CANCELLED:
                    viewHolder.tv_status.setText("买家已取消");
                    toOrderDetail(order, viewHolder, "查看订单详情");
                    break;
                case Constant.ORDER_STATUS_SELLER_CANCELLED:
                case Constant.ORDER_STATUS_SELLER_CANCEL_ON_PAID:
                    viewHolder.tv_status.setText("卖家已取消");
                    toOrderDetail(order, viewHolder, "查看订单详情");
                    break;

                case Constant.ORDER_STATUS_TRADE_SUCCESS:
                    viewHolder.tv_status.setText("交易成功");
                    toOrderDetail(order, viewHolder, "查看订单详情");
                    break;
                case Constant.ORDER_STATUS_REFUNDING:

                    viewHolder.tv_status.setText("退款中...");
                    toOrderDetail(order, viewHolder, "查看订单详情");
                    break;
                case Constant.ORDER_STATUS_CANCEL_REFUND:
                    viewHolder.tv_status.setText("取消退款");
                    toOrderDetail(order, viewHolder, "查看订单详情");
                    break;
                case Constant.ORDER_STATUS_REFUSE_REFUND:
                    viewHolder.tv_status.setText("拒绝退款");
                    toOrderDetail(order, viewHolder, "查看订单详情");
                    break;
                case Constant.ORDER_STATUS_AGREE_REFUND:
                    viewHolder.tv_status.setText("同意退款");
                    toOrderDetail(order, viewHolder, "查看订单详情");
                    break;
                case Constant.ORDER_STATUS_REFUND_COMPLETED:
                    viewHolder.tv_status.setText("退款完成");
                    toOrderDetail(order, viewHolder, "查看订单详情");
                    break;
                default:
                    viewHolder.tv_status.setText("竞价进行中...");
                    viewHolder.tv_tips.setVisibility(View.VISIBLE);
                    if (order.getAmount() < topic.getPrice()) {
                        viewHolder.tv_myAmount.setTextColor(context.getResources().getColor(R.color.rp_money_red_light));
                        viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_black));
                        viewHolder.tv_tips.setText("出价已经落后 ￥ " + Utils.numberFormat(topic.getPrice() - order.getAmount()) + " ，点我去继续出价");
                        viewHolder.tv_tips.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                OfferDialogV1 offerDialog = new OfferDialogV1(context, topic, new OfferDialogV1.InteractionListener() {
                                    @Override
                                    public void onOfferSuccess(double amount) {
                                        order.setAmount(amount);
                                        topic.setPrice(amount);
                                        notifyItemChanged(position);
                                    }
                                });
                                offerDialog.show();
                            }
                        });
                    } else {
                        viewHolder.tv_myAmount.setTextColor(context.getResources().getColor(R.color.text_black));
                        viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_black));
                        viewHolder.tv_tips.setText("目前是最高出价保持者");
                        viewHolder.tv_tips.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                OfferDialogV1 offerDialog = new OfferDialogV1(context, topic, new OfferDialogV1.InteractionListener() {
                                    @Override
                                    public void onOfferSuccess(double amount) {
                                        order.setAmount(amount);
                                        topic.setPrice(amount);
                                        notifyItemChanged(position);
                                    }
                                });
                                offerDialog.show();
                            }
                        });

                    }
                    viewHolder.itemView.setOnClickListener(v -> getFullTopic(topic.getId()));

                    break;
            }
            viewHolder.tv_date.setText(DateUtils.getTimestampString(order.getUpdated() != null ? order.getUpdated() : order.getCreated()));
        } else {
            context.startActivity(new Intent(context, OrderDetailActivity.class).putExtra(Constant.EXTRA_INFO_ORDER, order));
            switch (order.getStatus()) {
                case Constant.ORDER_STATUS_INIT:
                    viewHolder.tv_status.setText("等待支付");
                case Constant.ORDER_STATUS_PAID:
                    viewHolder.tv_status.setText("已支付");
                    break;
                case Constant.ORDER_STATUS_EXPIRED:
                    viewHolder.tv_status.setText("已过期");
                    break;
                case Constant.ORDER_STATUS_BUYER_CANCELLED:
                    viewHolder.tv_status.setText("已取消");
                    break;
                case Constant.ORDER_SEND_STATUS_SENT:
                    viewHolder.tv_status.setText("已发货");
                    break;
                case Constant.ORDER_SEND_STATUS_RECEIVED:
                    viewHolder.tv_status.setText("已收货");
                    break;
                case Constant.ORDER_STATUS_REFUNDING:
                    viewHolder.tv_status.setText("退款中...");
                    break;
                case Constant.ORDER_STATUS_REFUND_COMPLETED:
                    viewHolder.tv_status.setText("退款完成");
                    break;
            }

            viewHolder.tv_date.setText(DateUtils.getTimestampString(order.getUpdated() != null ? order.getUpdated() : order.getCreated()));
        }

        viewHolder.tv_myAmount.setText(Utils.numberFormat(order.getAmount()));
        viewHolder.itemView.setOnLongClickListener(v -> showDeleteDialog(order, position));

    }

    private void showAdvertisementOrder(Orders order, OfferViewHolder viewHolder) {
        Advertisement advertisement = order.getAdvertisement();
        if (advertisement == null) {
            Log.e(TAG, "showAdvertisementOrder: 广告信息为空");
            return;
        }
        advertisement.setoId(order.getId());//从数据库查数据的时候，没有查oId 字段，需要在这儿加上offerId,在activityResult中要使用
        viewHolder.tv_title.setText(advertisement.getTitle());
        viewHolder.tv_orderType.setText("[广告位]");
        Date startTime = order.getCreated();//订单创建时间是 广告位开始展示时间
        Date endTime = order.getExpiryDate();//过期时间是 广告位结束时间
        if (startTime == null || endTime == null) {
            return;
        }
        viewHolder.tv_date.setText(DateUtils.dateToString(startTime, "yyyy-MM-dd HH") + " 到 " + DateUtils.dateToString(endTime, "yyyy-MM-dd HH"));
        // viewHolder.tv_maxAmount.setText(Utils.numberFormat(advertisement.getAmount()));
        switch (order.getStatus()) {
            case Constant.ORDER_STATUS_TRADE_SUCCESS:
                viewHolder.tv_myAmount.setTextColor(context.getResources().getColor(R.color.text_black));
                viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.rp_money_red_light));
                viewHolder.tv_status.setText("竞价成功");
                viewHolder.tv_tips.setVisibility(View.VISIBLE);
                Date currentDate = new Date();
                Integer updateCount = advertisement.getUpdateCount();
                if (startTime.after(currentDate) || startTime.equals(currentDate)) {//如果广告展示还没开始或者广告位展示已经开始，但是还没有设置过广告展示内容，显示“去设置广告”
                    if (updateCount == null) {
                        viewHolder.tv_tips.setTextColor(context.getResources().getColor(R.color.top_bar_normal_bg));
                        viewHolder.tv_tips.setText("去设置广告");
                    } else {
                        viewHolder.tv_tips.setTextColor(context.getResources().getColor(R.color.text_black));
                        viewHolder.tv_tips.setText("广告已经设置");
                    }
                    viewHolder.itemView.setOnClickListener(v -> toSetAdvertisement(advertisement));
                } else if (endTime.after(currentDate)) {
                    if (updateCount == null) {
                        viewHolder.tv_tips.setTextColor(context.getResources().getColor(R.color.top_bar_normal_bg));
                        viewHolder.tv_tips.setText("去设置广告");
                        viewHolder.itemView.setOnClickListener(v -> toSetAdvertisement(advertisement));
                    } else {
                        viewHolder.tv_tips.setTextColor(context.getResources().getColor(R.color.text_black));
                        viewHolder.tv_tips.setText("广告展示中...");
                    }
                } else {
                    if (updateCount == null) {
                        viewHolder.tv_tips.setTextColor(context.getResources().getColor(R.color.text_gray));
                        viewHolder.tv_tips.setText("广告已过期");
                    } else {
                        viewHolder.tv_tips.setTextColor(context.getResources().getColor(R.color.text_gray));
                        viewHolder.tv_tips.setText("广告展示已经结束");
                    }
                }

                break;
            case Constant.ORDER_STATUS_OFFER_FAIL:
                viewHolder.tv_myAmount.setTextColor(context.getResources().getColor(R.color.text_gray));
                viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_gray));
                viewHolder.tv_status.setText("竞价失败");
                viewHolder.tv_tips.setVisibility(View.GONE);
                break;

            default:
                viewHolder.tv_status.setText("竞价进行中...");
                viewHolder.tv_tips.setVisibility(View.VISIBLE);
                if (order.getAmount() < advertisement.getAmount().doubleValue()) {
                    viewHolder.tv_myAmount.setTextColor(context.getResources().getColor(R.color.rp_money_red_light));
                    viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_black));
                    viewHolder.tv_tips.setTextColor(context.getResources().getColor(R.color.top_bar_normal_bg));
                    viewHolder.tv_tips.setText("出价已经落后 ￥ " + Utils.numberFormat(advertisement.getAmount().doubleValue() - order.getAmount()) + " ，点我去继续出价");

                } else {
                    viewHolder.tv_myAmount.setTextColor(context.getResources().getColor(R.color.text_black));
                    viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_black));
                    viewHolder.tv_tips.setTextColor(context.getResources().getColor(R.color.top_bar_normal_bg));
                    viewHolder.tv_tips.setText("目前是最高出价保持者");
                }
                viewHolder.itemView.setOnClickListener(v -> ((Activity) context).
                        startActivityForResult(new Intent(context, AdvertisementActivity.class).putExtra("advertisement", advertisement), REQUEST_CODE_OFFER));

                break;
        }
    }

    private void toSetAdvertisement(Advertisement advertisement) {
        ((Activity) context).startActivityForResult(new Intent(context, SetAdvertisementContentActivity.class).putExtra("advertisement", advertisement), REQUEST_CODE_SET_ADVERTISEMENT);
    }

    private boolean showDeleteDialog(Orders order, int position) {

        ConfirmDialog dialog = new ConfirmDialog(context, "提醒", "删除订单后，该订单将不再显示", true);
        dialog.setConfirmListener(() -> deleteOrder(order, position));
        dialog.show();
        return true;
    }

    private void deleteOrder(Orders order, int position) {
        List<String> orderIdList = new ArrayList<>();
        orderIdList.add(order.getId());
        if (order.getuId().equals(UserProfileManager.getInstance().getLoginUserInfo().getuId())) {

            RetrofitManager.getInstance().createRequest(OrderService.class)
                    .deleteOrdersForBuyer(orderIdList)
                    .enqueue(new Callback<CommonResult>() {
                        @Override
                        public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                            CommonResult result = response.body();
                            if (!response.isSuccessful() || result == null) {
                                Log.e(TAG, "onResponse: " + response.message());
                                return;
                            }

                            if (result.isError()) {
                                Log.e(TAG, "onResponse: " + result.getMsg());
                                return;
                            }
                            Log.d(TAG, "onResponse: 订单删除完成");
                            ordersList.remove(position);
                            notifyItemRemoved(position);
                            notifyItemRangeChanged(position, ordersList.size() - position);
                        }

                        @Override
                        public void onFailure(Call<CommonResult> call, Throwable t) {
                            Log.e(TAG, "onFailure: " + t.getMessage());
                        }
                    });
        } else {
            RetrofitManager.getInstance().createRequest(OrderService.class)
                    .deleteOrdersForSeller(orderIdList)
                    .enqueue(new Callback<CommonResult>() {
                        @Override
                        public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                            CommonResult result = response.body();
                            if (!response.isSuccessful() || result == null) {
                                Log.e(TAG, "onResponse: " + response.message());
                                return;
                            }

                            if (result.isError()) {
                                Log.e(TAG, "onResponse: " + result.getMsg());
                                return;
                            }
                            Log.d(TAG, "onResponse: 订单删除完成");
                            ordersList.remove(position);
                            notifyItemRemoved(position);
                            notifyItemRangeChanged(position, ordersList.size() - position);

                        }

                        @Override
                        public void onFailure(Call<CommonResult> call, Throwable t) {
                            Log.e(TAG, "onFailure: " + t.getMessage());
                        }
                    });

        }


    }

    private void toOrderDetail(Orders order, OfferViewHolder viewHolder, String message) {
        viewHolder.tv_tips.setText(message);
        viewHolder.itemView.setOnClickListener(v -> ((Activity) context).startActivityForResult(new Intent(context, OrderDetailActivity.class).putExtra(Constant.EXTRA_INFO_ORDER, order), REQUEST_CODE_TO_ORDER_DETAIL));
    }

    private void getFullTopic(String topicId) {

        RetrofitManager.getInstance().createRequest(TopicService.class)
                .get(topicId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            return;
                        }
                        if (body.isError()) {
                            return;
                        }
                        Log.d(TAG, "onResponse: 获取完成topic 完成");
                        JSONObject object = (JSONObject) body.getData();
                        if (object == null) {
                            return;
                        }
                        Topic topic = object.toJavaObject(Topic.class);
                        context.startActivity(new Intent(context, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });


    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {

        if (ordersList.size() == 0) {
            return 1;
        }
        return ordersList.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (ordersList.size() == 0) {
            return ITEM_TYPE_NO_DATA;
        }
        return ordersList.get(position).getType();


    }

    class NoDataViewHolder extends RecyclerView.ViewHolder {


        public NoDataViewHolder(View itemView) {
            super(itemView);

        }
    }


    class OfferViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_title)
        TextView tv_title;
        @BindView(R.id.tv_status)
        TextView tv_status;
        @BindView(R.id.tv_date)
        TextView tv_date;
        @BindView(R.id.tv_my_amount)
        TextView tv_myAmount;
        @BindView(R.id.tv_max_amount)
        TextView tv_maxAmount;
        @BindView(R.id.tv_tips)
        TextView tv_tips;
        @BindView(R.id.tv_order_type)
        TextView tv_orderType;

        public OfferViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

}